package com.wakala.employment.fragment.recruit;

import android.content.Intent;
import android.util.ArraySet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.hjq.toast.Toaster;
import com.kongzue.dialogx.dialogs.InputDialog;
import com.kongzue.dialogx.interfaces.OnInputDialogButtonClickListener;
import com.kongzue.dialogx.style.MIUIStyle;
import com.kongzue.dialogx.util.TextInfo;
import com.leaf.library.StatusBarUtil;
import com.wakala.employment.R;
import com.wakala.employment.adapter.base.FlowTagSimpleAdapter;
import com.wakala.employment.adapter.jobCategory.JobCategoryAttrTreeVo;
import com.wakala.employment.adapter.jobCategory.JobCategoryTreeVo;
import com.wakala.employment.core.BaseFragment;
import com.wakala.employment.core.constants.Constants;
import com.wakala.employment.databinding.FragmentTagEditBinding;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xui.utils.XToastUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.flowlayout.FlowTagLayout;
import com.xuexiang.xutil.common.RegexUtils;
import com.xuexiang.xutil.display.DensityUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

import co.lujun.androidtagview.TagContainerLayout;
import co.lujun.androidtagview.TagView;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link TagEditFragment#} factory method to
 * create an instance of this fragment.
 */
@Page(anim = CoreAnim.none)
public class TagEditFragment extends BaseFragment<FragmentTagEditBinding> implements View.OnClickListener {


    private int requestCode;

    /**
     * 可选标签容器
     */
    FlowTagLayout mSourceTagLayout;
    /**
     * 已选标签容器
     */
    TagContainerLayout mTagContainerLayout;

    /**
     * 可选标签
     */
    private List<String> sourceTagList = new ArrayList<>();
    private Set<String> selectedTagList = new ArraySet<>();
    private Set<String> customTagList = new ArraySet<>();

    @NonNull
    @Override
    protected FragmentTagEditBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentTagEditBinding.inflate(inflater, container, attachToRoot);
    }

    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle();
        titleBar.setTitle("标签选择");
        titleBar.setTitleColor(R.color.black);
        titleBar.setLeftTextColor(R.color.black);
        titleBar.setLeftImageDrawable(getResources().getDrawable(R.drawable.icon_arrow_back));
        titleBar.setBackgroundResource(R.color.white);//设置标题栏背景颜色
        StatusBarUtil.setDarkMode(getActivity());
        //设置状态栏背景颜色，如果设置为 Color.TRANSPARENT 将会隐藏状态栏
        getActivity().getWindow().setStatusBarColor(getResources().getColor(R.color.white));
        return titleBar;
    }

    @Override
    protected void initListeners() {
        super.initListeners();
        binding.tvAddTag.setOnClickListener(this);//添加自定义标签
        binding.btnSave.setOnClickListener(this);//保存
    }

    @Override
    protected void initArgs() {
        super.initArgs();
        //initArgs执行时间早于initView
        requestCode =getRequestCode();
    }

    /**
     * 初始化职位标签
     */
    private void initJobData(){
        sourceTagList.add("长期工");
        sourceTagList.add("短期工");
        sourceTagList.add("零工");
        sourceTagList.add("兼职");
        sourceTagList.add("户外");
        sourceTagList.add("准时发薪");
        for(String tagName:sourceTagList){
            mSourceTagLayout.addTag(tagName);
        }
    }

    /**
     * 初始化福利标签
     */
    private void initWelfareData(){
        sourceTagList.add("包吃");
        sourceTagList.add("包住");
        sourceTagList.add("高温补贴");
        sourceTagList.add("保险");
        sourceTagList.add("社保");
        sourceTagList.add("餐补");
        for(String tagName:sourceTagList){
            mSourceTagLayout.addTag(tagName);
        }
    }

    @Override
    protected void initViews() {
        mSourceTagLayout = binding.flowlayoutSource;
        //
        FlowTagSimpleAdapter tagAdapter = new FlowTagSimpleAdapter<String>(getContext());
        mSourceTagLayout.setAdapter(tagAdapter);
        mSourceTagLayout.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_MULTI);//可多选
        mSourceTagLayout.setOnTagSelectListener((parent, position, selectedList) -> getSelectedText(parent, selectedList));
        //
        //初始化tagViewLayout
        mTagContainerLayout = (TagContainerLayout) findViewById(R.id.tagcontainerLayout);
        mTagContainerLayout.setCrossColor(getResources().getColor(R.color.colorPrimary));
        mTagContainerLayout.setCrossLineWidth(DensityUtils.dip2px(2));
        mTagContainerLayout.setOnTagClickListener(new TagView.OnTagClickListener() {
            @Override
            public void onTagClick(int i, String s) {

            }

            @Override
            public void onTagLongClick(int i, String s) {

            }

            @Override
            public void onSelectedTagDrag(int i, String s) {

            }

            @Override
            public void onTagCrossClick(int position) {
                String tagText = mTagContainerLayout.getTagText(position);
                if(!sourceTagList.contains(tagText)){
                    customTagList.removeIf(item->item.equals(tagText));
                    mTagContainerLayout.removeTag(position);
                    return;
                }
                mTagContainerLayout.removeTag(position);
                //
                selectedTagList.removeIf(item->item.equals(tagText));
                //
                List<Integer> postSelectedIndex = new ArrayList<>();
                List<Integer> selectedIndexList =  mSourceTagLayout.getSelectedIndexs();
                for (int index : selectedIndexList) {
                    String sourceTag = (String) mSourceTagLayout.getAdapter().getItem(index);
                    if(!sourceTag.equals(tagText)){
                        postSelectedIndex.add(index);
                    }
                }

                if(!postSelectedIndex.isEmpty()){
                    mSourceTagLayout.setSelectedPositions(postSelectedIndex);
                }else {
                    mSourceTagLayout.clearSelection();
                }
            }
        });
        //初始化标签
        if(requestCode== Constants.REQ_RESULT_113){
            initJobData();
        }else if(requestCode==Constants.REQ_RESULT_114){
            initWelfareData();
        }
    }

    /**
     *
     * @param parent  当前操作的FlowTagLayout
     * @param selectedList 选择的所有tag
     * @return
     */
    private void getSelectedText(FlowTagLayout parent, List<Integer> selectedList) {
        selectedTagList.clear();
        for (int index : selectedList) {
            String tagName = (String) parent.getAdapter().getItem(index);
            if(!selectedTagList.contains(tagName)){
                selectedTagList.add(tagName);
            }
        }
        //
        refreshSelectedTagLayout();
    }

    private void refreshSelectedTagLayout(){
        mTagContainerLayout.removeAllTags();
        Set<String> tempTagList = new ArraySet<>();
        tempTagList.addAll(selectedTagList);
        tempTagList.addAll(customTagList);
        for(String tagName:tempTagList){
            mTagContainerLayout.addTag(tagName);
        }
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if(id==R.id.tv_add_tag){
            addCustomTag();
        } else if (id == R.id.btn_save) {
            //保存
            savaTags();
        }
    }

    /**
     * 添加自定义标签
     */
    private void addCustomTag() {
        //InputDialog inputDialog = InputDialog.build().setStyle(MIUIStyle.style()).setTitle("系统提示").setMessage("请输入招工联系电话");
        new InputDialog("自定义标签", "注意:违规内容可能导致封号", "添加", "取消", "").setMessageTextInfo(new TextInfo().setFontSize(12))
                .setCancelable(false)
                .setOkButton(new OnInputDialogButtonClickListener<InputDialog>() {
                    @Override
                    public boolean onClick(InputDialog baseDialog, View v, String inputStr) {
                        if (isUTagName(inputStr) && !selectedTagList.contains(inputStr)) {
                            customTagList.add(inputStr);
                            refreshSelectedTagLayout();
                            baseDialog.dismiss();
                        } else {
                            Toaster.show("输入标签内容不合法");
                        }
                        return true;
                    }
                }).setStyle(MIUIStyle.style())
                .show();
    }
    public static boolean isUTagName(CharSequence input) {
        return isMatch("^[\\w\\u4e00-\\u9fa5]{2,4}(?<!_)$", input);
    }
    public static boolean isMatch(String regex, CharSequence input) {
        return input != null && input.length() > 0 && Pattern.matches(regex, input);
    }


    private void savaTags(){
        Intent intent=new Intent();
        ArrayList<String> mSelectedList = new ArrayList<>();
        mSelectedList.addAll(selectedTagList);
        mSelectedList.addAll(customTagList);
        intent.putStringArrayListExtra("selectedTagList",mSelectedList);
        setFragmentResult(requestCode,intent);
        popToBack();
    }
}